home *** CD-ROM | disk | FTP | other *** search
- Path: mudskipper.cac.psu.edu!user
- From: fcusack@tdx.org (frank.)
- Newsgroups: comp.lang.c
- Subject: Re: Union type
- Date: Thu, 11 Apr 1996 09:25:00 -0400
- Organization: Soylent Green is People!!
- Message-ID: <fcusack-1104960925000001@mudskipper.cac.psu.edu>
- References: <4kh43f$h4f@dewey.csun.edu>
- NNTP-Posting-Host: mudskipper.cac.psu.edu
-
- In article <4kh43f$h4f@dewey.csun.edu>, kc44097@csun.edu (chen) wrote:
-
- > I have a question about union,can anyonegive me some advice?
- > Please e-mail me
- > kc44097@huey.csun.edu
- > Thankx
- > -------------------------------------------------------------
- >
- > #include <stdio.h>
- >
- > union {
- > int integer;
- > float floating;
- > } myUnion;
- >
- >
- > main()
- > {
- >
- > myUnion.integer = 1;
- >
- > printf("The value of integer is %d\n", myUnion.integer);
- > printf("The value of floating is %f\n\n", myUnion.floating);
- > printf("The value of \"cast\" is %f\n", (float) myUnion.integer);
- > printf("The value of \"magic\" is %f\n\n", myUnion.integer);
- > printf("The meaning of life ``%d''\n", (int) myUnion.floating);
- > return (0);
- > }
- >
- > The optput is :
- >
- > The value of integer is 1
- > The value of floating is 0.000000
- > The value of cast is 1.000000
- > The value of magic is 0.000000
- > The meaning of life ``0''
- >
- >
- > My question is : Why myUnion.integer is 1 but myUnion.floating is
- > 0.000000;Why myUnion.integer change to 0.000000 in 4th printf(),
- > and why myUnion.floating is 0 in 5th printf()?
-
- When retreiving the value of a union, you must retrieve the same type as
- most recently assigned. Other behavior is undefined. IOW, don't do it!!
-
- ie, in your example, since you assigned a value to the integer value of
- your union, you can ONLY retrieve the integer value.
-
- ~Frank
- - Through the modem, past the router, over the firewall.. nothing but Net -
- - PGP ID: 1C0F6685 | NCB#56 | Visit me --> http://www.tdx.org/~fcusack/ -
-